package org.weso.lodin.utils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.weso.lodin.exceptions.DocumentBuilderException;
import org.weso.lodin.exceptions.LodinModelException;
import org.weso.lodin.generated.Datawb;

public class DataWBXMLBind {
private static Logger logger = Logger.getLogger(DataWBXMLBind.class);
	
	public static final String PACKAGE_NAME = Datawb.class.getPackage().getName();
	
	private Unmarshaller unmarshaller;
	private Marshaller marshaller;
	
	private DataWBXMLBind() {
		try {
			JAXBContext jc = JAXBContext.newInstance(PACKAGE_NAME);
			this.unmarshaller = jc.createUnmarshaller();
			this.marshaller = jc.createMarshaller();
			//            unmarshaller.setEventHandler(eventHandler);
			//            marshaller.setEventHandler(eventHandler);
		} catch(JAXBException e) {
			//
		}
	}

	public Datawb restoreIndicator(Node node) {
		try {
			return (Datawb) unmarshaller.unmarshal(node);	
			
			//return (IndicatorType) unmarshaller.unmarshal(node);
		} catch (JAXBException je) {
			je.printStackTrace();
			throw new LodinModelException(je, "Data: Unmarshalling indicator.");
		}
	}
	
	
	public Document serializeIndicator(Datawb concept) {
		logger.debug("Serializing dataset XML");
		try {
			Document doc = DocumentBuilderHelper.getEmptyDocument();
			marshaller.marshal(concept, doc);
			return doc;
		} catch (JAXBException je) {
			throw new LodinModelException(je, "Data: Marshalling indicator.");
		} catch (DocumentBuilderException e) {
			throw new LodinModelException(e, "Data: Marshalling indicator.");
		}
   
	}

	/**
	 * Singleton field
	 */
	private static DataWBXMLBind instance;
	
	/**
	 * Singleton method
	 * 
	 * @return The singleton instance of this class 
	 * @throws XmlBindException
	 */
	public static DataWBXMLBind getInstance() {
		if (instance == null) {
			instance = new DataWBXMLBind();
		}
		return instance;
	}	
}
